# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools, osv, _
from odoo.exceptions import ValidationError, Warning
from datetime import datetime
from dateutil.relativedelta import relativedelta
from uuid import uuid1


APPLY_STATE = [('pending', '待审批'), ('approved', '审批通过'), ('reject', '审批未通过')]

class FilingMaintenanceApply(models.Model):
    """
    维保单位备案审核
    """

    # 维保公司的维保星级
    AVILABLE_MAINTENNANCE_STARS = [
        ('-1', '没有星级'),
        ('0', '一星级'),
        ('1', '二星级'),
        ('2', '三星级'),
        ('3', '四星级'),
        ('4', '五星级'),
    ]
    _name = "tyibs.base.filing.maintenance.apply"
    _order = "id desc"

    # enterprise_id并不在显示范围内
    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string=u"单位名称", required=True, default=lambda self: self.env.user.main_company_id.id)
    # 单位名称
    name = fields.Char(string=u"单位名称", size=100, required=True, index=True, search=True)
    # 单位编码
    # code = fields.Char(string=u"单位编码", size=100, required=True, index=True, search=True)
    # 社会统一信用代码
    trust_code = fields.Char(string=u'社会统一信用代码', required=False, size=100)
    # 省
    province_id = fields.Many2one('tyibs.base.province', string=u'所属省份', required=True)
    # 市
    city_id = fields.Many2one('tyibs.base.province.city', string=u'所属城市', domain="[('province_id', '=', province_id)]",
                              required=True)
    # 区
    area_id = fields.Many2one('tyibs.base.province.city.area', string=u'所属区', domain="[('city_id', '=', city_id)]",
                              required=True)
    # 维保星级
    maintenance_star = fields.Selection(AVILABLE_MAINTENNANCE_STARS, string=u"维保星级", index=True)
    # 详细地址
    address = fields.Char(string=u"详细地址", size=300)
    legal_person = fields.Char(string=u"法人", size=40)
    legal_person_mobile = fields.Char(string=u"法人电话", size=40)
    legal_identity_card = fields.Char(string=u"法人身份证", size=40)
    company_telephone = fields.Char(string=u"公司固话")
    company_email = fields.Char(string=u"公司邮箱")

    # 异地或本地维保
    local_or_remote = fields.Selection([('local', '本地'), ('remote', '异地')], u"异地/本地")
    # 维保负责人
    maintenance_man = fields.Char(string=u"维保负责人", size=100)
    # 维保负责人手机
    maintenance_man_mobile = fields.Char(string=u"维保负责人手机", size=20)
    # 应急救援负责人
    save_man = fields.Char(string=u"应急救援负责人", size=100)
    # 应急救援负责人手机
    save_man_mobile = fields.Char(string=u"救援负责人手机", size=20)
    # 许可证编号
    special_card_num = fields.Char(string=u"许可证编号", size=100, required=True)
    # 许可证有效日期
    special_card_period = fields.Date(string=u"许可证有效期", required=True)
    # 许可证颁发单位
    special_card_approver = fields.Char(string=u"许可证颁发单位", size=100, required=True)
    # 许可证附件
    special_card_att_id = fields.Binary(string=u"许可证附件", attachment=True, public=True, required=True)
    # 营业执照
    attachment_ids = fields.Many2many("ir.attachment", string="营业执照")
    # 员工信息
    employee_ids = fields.Many2many('tyibs.base.maintenance.company.employee', "tyibs_base_filing_maintenance_apply_employee_rel", "apply_company_id", "employee_id", string=u"员工")
    # 申请人
    applicant_person = fields.Many2one('res.users', string=u"申请人", default=lambda self: self.env.uid)

    # 申请时间
    applicant_time = fields.Datetime(string=u"申请时间", default=datetime.utcnow())

    # 审批状态
    state = fields.Selection(APPLY_STATE, string=u'审批状态', default='pending', readonly=True)
    log_ids = fields.Many2many("tyibs.base.common.log", "tyibs_base_main_company_apply_common_log_rel", "apply_id",
                               "log_id",
                               domain="[('res_model', '=', 'tyibs.base.filing.maintenance.apply'), ('res_id', '=', id)]",
                               string=u"审核记录")

    @api.model
    def create(self, vals):
        if vals.get("employee_ids", False):
            vals["employee_ids"] = [(4, item[1], False) for item in vals.get("employee_ids")]
        return super(FilingMaintenanceApply, self).create(vals)

    @api.multi
    def write(self, vals):
        """
        审核过的工单不可以修改
        :param vals:
        :return:
        """
        if self.state == "approved":
            raise Warning(u"工单已经审核通过，不可以修改。")
        vals["state"] = "pending"
        return super(FilingMaintenanceApply, self).write(vals)

    def origin_write(self, vals):
        return super(FilingMaintenanceApply, self).write(vals)

    @api.one
    def refresh_employee(self):
        all_employee_ids = self.enterprise_id.employee_ids.filtered(lambda emp:not emp.has_dimission and emp.certificate_valid)
        if self.employee_ids == all_employee_ids:
            raise Warning(u"员工没有变化")
        self.write({
            'employee_ids': [[6, False, all_employee_ids.ids]],
            'log_ids': [(0, False, {
                'res_model': self._name,
                'res_id': self.id,
                'user_id': self.env.uid,
                'content': u"变更员工",
                'time': datetime.utcnow()
            })]
        })


    @api.one
    def approve(self):
        """
        审核通过
        :return:
        """
        # if self.local_or_remote == "remote" and self.env.user.qs_level != "1":
        #     raise Warning(u"异地维保单位只有市局可以审核。")

        res = self.origin_write({
            'state': 'approved',
            'log_ids': [(0, False, {
                'res_model': self._name,
                'res_id': self.id,
                'user_id': self.env.uid,
                'content': u"审核通过",
                'time': datetime.utcnow()
            })]
        })
        self.save_maintenance_commpany()
        return res

    def save_maintenance_commpany(self):
        """
        更新维保单位信息
        :return:
        """
        format_str = "%Y-%m-%d"
        current_date = datetime.now().strftime(format_str)
        interval_years = 4 if self.local_or_remote == "local" else 1

        origin_vals = {
            "filing_date": current_date,
            "next_filing_date": (datetime.now() + relativedelta(years=interval_years)).strftime(format_str)
        }

        if self.name != "":
            origin_vals["name"] = self.name
        if self.trust_code != "":
            origin_vals["trust_code"] = self.trust_code
        if self.province_id != "":
            origin_vals["province_id"] = self.province_id.id
        if self.city_id != "":
            origin_vals["city_id"] = self.city_id.id
        if self.area_id != "":
            origin_vals["area_id"] = self.area_id.id
        if self.maintenance_star != "":
            origin_vals["maintenance_star"] = self.maintenance_star
        if self.address != "":
            origin_vals["address"] = self.address
        if self.legal_person != "":
            origin_vals["legal_person"] = self.legal_person
        if self.legal_identity_card != "":
            origin_vals["legal_identity_card"] = self.legal_identity_card
        if self.legal_person_mobile != "":
            origin_vals["legal_person_mobile"] = self.legal_person_mobile
        if self.company_telephone != "":
            origin_vals["company_telephone"] = self.company_telephone
        if self.company_email != "":
            origin_vals["company_email"] = self.company_email
        if self.local_or_remote != "":
            origin_vals["local_or_remote"] = self.local_or_remote
        if self.maintenance_man != "":
            origin_vals["maintenance_man"] = self.maintenance_man
        if self.maintenance_man_mobile != "":
            origin_vals["maintenance_man_mobile"] = self.maintenance_man_mobile
        if self.save_man != "":
            origin_vals["save_man"] = self.save_man
        if self.save_man_mobile != "":
            origin_vals["save_man_mobile"] = self.save_man_mobile
        if self.special_card_num != "":
            origin_vals["special_card_num"] = self.special_card_num
        if self.special_card_period != "":
            origin_vals["special_card_period"] = self.special_card_period
        if self.special_card_approver != "":
            origin_vals["special_card_approver"] = self.special_card_approver
        if self.special_card_att_id != "":
            origin_vals["special_card_att_id"] = self.special_card_att_id
        if self.attachment_ids != "":
            origin_vals["attachment_ids"] = [[6, False, self.attachment_ids.ids]]
        self.enterprise_id.write(origin_vals)

    @api.onchange("enterprise_id")
    def _onchange_enterprise_id(self):
        """
        选择哪一个维保单位后，自动带出相关资料
        :return:
        """
        company = self.enterprise_id
        if company:
            value = {
                "name": company.name,
                "trust_code": company.trust_code,
                "province_id": company.province_id,
                "city_id": company.city_id,
                "area_id": company.area_id,
                "maintenance_star": company.maintenance_star,
                "address": company.address,
                "company_telephone": company.company_telephone,
                "company_email": company.company_email,
                "legal_person": company.legal_person,
                "legal_person_mobile": company.legal_person_mobile,
                "legal_identity_card": company.legal_identity_card,
                "local_or_remote": company.local_or_remote,
                "maintenance_man": company.maintenance_man,
                "maintenance_man_mobile": company.maintenance_man_mobile,
                "save_man": company.save_man,
                "save_man_mobile": company.save_man_mobile,
                "special_card_num": company.special_card_num,
                "special_card_period": company.special_card_period,
                "special_card_approver": company.special_card_approver,
                "special_card_att_id": company.special_card_att_id,
            }
            if company.attachment_ids:
                value["attachment_ids"] = [[6, False, company.attachment_ids.ids]]
            if company.employee_ids:
                value["employee_ids"] = [[6, False, company.employee_ids.filtered(lambda item: not item.has_dimission and item.certificate_valid).ids]]
            return {"value": value}

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        if context.get("search_from", False) == "qs_area":
            args.append(("area_id", '=', self.env.user.qs_company_id.area_id.id))
        elif context.get("search_from", False) == "main_menu":
            args.append(("enterprise_id", "=", self.env.user.main_company_id.id))
        return super(FilingMaintenanceApply, self).search(args, offset, limit, order, count)


class UniversalStatusRecord(models.Model):
    """
    审批记录
    """
    _name = "tyibs.base.universal.status.record"
    name = fields.Many2one('tyibs.base.filing.maintenance.apply', stirng=u'备案编号', szie=200)
    processing_time = fields.Datetime(string=u'处理时间')
    processing_content = fields.Char(string=u'处理内容', size=200)
    processing_person = fields.Char(string=u'处理人', size=50)


# class FilingMaintenanceEmployeeApply(models.Model):
#     """
#     维保单位审核记录中的维保单位员工信息
#     """
#     _name = "tyibs.base.filing.maintenance.company.employee.apply"
#     _description = u"员工信息"
#     _order = 'name'
#
#     name = fields.Char(string=u"员工名称", size=50, index=True)
#     code = fields.Char(string=u"员工编号", size=100)
#     mobile = fields.Char(string=u'手机号', size=30)
#     phone = fields.Char(u'座机电话', size=50)
#     identification_id = fields.Char(string=u'身份证号', size=40)
#     email = fields.Char(string=u'邮箱', size=100)
#     position = fields.Char(u"职位", size=50)
#     birthday = fields.Date(u'出生日期')
#     family_phone = fields.Char(u'家庭电话', size=50)
#
#     gender = fields.Selection([
#         ('male', u'男性'),
#         ('female', u'女性'),
#         ('other', u'其他')
#     ], string=u"性别")
#     marital = fields.Selection([
#         ('single', u'单身'),
#         ('married', u'已婚'),
#         ('widower', u'丧偶'),
#         ('divorced', u'离异')
#     ], string=u'婚姻状态')
#     enterprise_apply_id = fields.Many2one("tyibs.base.filing.maintenance.apply", string=u"所属单位")
#     image = fields.Binary(u"中等大小照片", attachment=True)
#     certificate_ids = fields.One2many("tyibs.base.filing.employee.certificate.apply", "employee_id",
#                                       string=u"员工证书")
#     notes = fields.Text('备注')
#
#     @api.model
#     def create(self, vals):
#         if vals.get("mobile", False):
#             record = self.env["tyibs.base.maintenance.company.employee"].search([("mobile", "=", vals.get("mobile"))])
#             if record:
#                 raise Warning(u"维保人员手机号%s已存在,请确认。" % vals.get("mobile"))
#         if vals.get("identification_id", False):
#             record = self.env["tyibs.base.maintenance.company.employee"].search(
#                 [("identification_id", "=", vals.get("identification_id"))])
#             if record:
#                 raise Warning(u"身份证号为%s的人员已存在，请确认。" % vals.get("identification_id"))
#         if vals.get("code", False):
#             record = self.env["tyibs.base.maintenance.company.employee"].search([("code", "=", vals.get("code"))])
#             if record:
#                 raise Warning(u"员工编号为%s的人员已存在，请确认。" % vals.get("code"))
#         return super(FilingMaintenanceEmployeeApply, self).create(vals)
#
#
# class FilingEmployeeCertificateAddApply(models.Model):
#     """
#     维保单位员工证书
#     """
#     _name = "tyibs.base.filing.employee.certificate.apply"
#     _description = u"维保员工证书审核"
#     _rec_name = "code"
#
#     employee_id = fields.Many2one("tyibs.base.filing.maintenance.company.employee.apply", string=u"所属审核员工",
#                                   required=True)
#     card_category_id = fields.Many2one("tyibs.base.maintenance.card.category", string=u"证书类型", required=True)
#     code = fields.Char(string=u"证书编号", size=100, required=True)
#     period = fields.Date(string=u"过期时间")
#     card_attach_id = fields.Binary(string=u"缩略图", attachment=True, public=True)


class FilingUserCompanyApply(models.Model):
    """
    使用单位注册审核
    """

    _name = "tyibs.base.filing.user.company.apply"
    _order = "id desc"

    use_company_id = fields.Many2one("tyibs.base.lift.use.company", string="使用单位")

    trust_code = fields.Char(string=u"社会统一信用代码", required=True)

    name = fields.Char(string=u'单位名称', size=100, required=True)

    linkman = fields.Char(string=u'联系人', size=20, required=True)

    linkman_tel = fields.Char(string=u'联系电话', size=15)

    linkman_phone = fields.Char(string=u'手机号码', size=30, required=True)

    linkman_email = fields.Char(string=u'电子邮箱', size=50)

    province_id = fields.Many2one('tyibs.base.province', string=u'所属省份', required=True)

    city_id = fields.Many2one('tyibs.base.province.city', string=u'所属城市', domain="[('province_id', '=', province_id)]",
                              required=True)
    area_id = fields.Many2one('tyibs.base.province.city.area', string=u'所属区', domain="[('city_id', '=', city_id)]",
                              required=True)
    address_detail = fields.Char(string=u'详细地址', size=100, required=True)

    login = fields.Char(string=u"登录账号")
    password = fields.Char(string=u"密码")

    # 申请时间
    applicant_time = fields.Datetime(string=u"申请时间")
    # 审批状态
    state = fields.Selection(APPLY_STATE,
                             string=u'审批状态', default='pending')
    change_logs_ids = fields.One2many("tyibs.base.filing.change.log", compute="_compute_relation_logs", string=u"变更内容")
    log_ids = fields.Many2many("tyibs.base.common.log", "tyibs_base_use_company_apply_common_log_rel", "apply_id",
                               "log_id",
                               domain="[('res_model', '=', 'tyibs.base.filing.user.company.apply'), ('res_id', '=', id)]",
                               string=u"审核记录")
    remark = fields.Text(string=u"备注")

    def _compute_relation_logs(self):
        for item in self:
            item.change_logs_ids = self.env["tyibs.base.filing.change.log"].search(
                [('res_model', '=', self._name), ('res_id', '=', item.id)])

    def origin_write(self, vals):
        # 跳过write的方法直接走父类write
        return super(FilingUserCompanyApply, self).write(vals)

    # @api.one
    def approve(self):
        """
        审核通过
        :return:
        """
        vals = {
            'state': 'approved',
            'log_ids': [(0, False, {
                'res_model': self._name,
                'res_id': self.id,
                'user_id': self.env.uid,
                'content': u"审核通过",
                'time': datetime.utcnow()
            })]
        }

        # 判断哪些要改
        origin_vals = {}
        if self.name != "":
            origin_vals["name"] = self.name

        if self.trust_code != "":
            origin_vals["trust_code"] = self.trust_code

        if self.linkman != "":
            origin_vals["linkman"] = self.linkman

        if self.linkman_tel != "":
            origin_vals["linkman_tel"] = self.linkman_tel

        if self.linkman_phone != "":
            origin_vals["linkman_phone"] = self.linkman_phone

        if self.linkman_email != "":
            origin_vals["linkman_email"] = self.linkman_email

        if self.province_id != "":
            origin_vals["province_id"] = self.province_id.id

        if self.city_id != "":
            origin_vals["city_id"] = self.city_id.id

        if self.area_id != "":
            origin_vals["area_id"] = self.area_id.id

        if self.address_detail != "":
            origin_vals["address_detail"] = self.address_detail

        if origin_vals:
            self.use_company_id.write(origin_vals)

        super(FilingUserCompanyApply, self).write(vals)

    @api.model
    def create(self, vals):
        vals["applicant_person"] = self.env.uid
        vals["applicant_time"] = datetime.utcnow()
        record = super(FilingUserCompanyApply, self).create(vals)
        # 生成变更记录
        record.generate_change_log(vals)
        return record

    # @api.multi
    # def write(self, vals):
    #     # 传入的参数中没有使用单位ID就重新取一编
    #     if not vals.get('use_company_id', False):
    #         vals["use_company_id"] = self.use_company_id.id
    #     # 删除原有变更记录
    #     self.change_logs_ids.unlink()
    #     # 生成新的变更记录
    #     self.generate_change_log(vals)
    #     # 重新写入申请人和申请时间
    #     vals["applicant_person"] = self.env.uid
    #     vals["applicant_time"] = datetime.utcnow()
    #     vals["reviewer_person"] = None
    #     vals["reviewer_time"] = None
    #     vals["state"] = "pending"
    #     return super(FilingUserCompanyApply, self).write(vals)

    def generate_change_log(self, vals):

        # 生成变更记录
        log_vals = {"res_model": self._name, "res_id": self.id}
        use_company_id = self.env["tyibs.base.lift.use.company"].browse(vals.get("use_company_id"))
        name = vals.get("name", False)

        change_log_model = "tyibs.base.filing.change.log"
        if name and name != use_company_id.name:
            log_vals["field_name"] = u"单位名称"
            log_vals["before_change"] = use_company_id.name
            log_vals["after_change"] = name
            self.env[change_log_model].create(log_vals)

        trust_code = vals.get("trust_code", False)
        if trust_code and trust_code != use_company_id.trust_code:
            log_vals["field_name"] = u"社会统一信用代码"
            log_vals["before_change"] = use_company_id.trust_code
            log_vals["after_change"] = trust_code
            self.env[change_log_model].create(log_vals)

        linkman = vals.get("linkman", False)
        if linkman and linkman != use_company_id.linkman:
            log_vals["field_name"] = u"联系人"
            log_vals["before_change"] = use_company_id.linkman
            log_vals["after_change"] = linkman
            self.env[change_log_model].create(log_vals)

        linkman_tel = vals.get("linkman_tel", False)
        if linkman_tel and linkman_tel != use_company_id.linkman_tel:
            log_vals["field_name"] = u"联系电话"
            log_vals["before_change"] = use_company_id.linkman_tel
            log_vals["after_change"] = linkman_tel
            self.env[change_log_model].create(log_vals)

        linkman_phone = vals.get("linkman_phone", False)
        if linkman_phone and linkman_phone != use_company_id.linkman_phone:
            log_vals["field_name"] = u"手机号码"
            log_vals["before_change"] = use_company_id.linkman_phone
            log_vals["after_change"] = linkman_phone
            self.env[change_log_model].create(log_vals)

        linkman_email = vals.get("linkman_email", False)
        if linkman_email and linkman_email != use_company_id.linkman_email:
            log_vals["field_name"] = u"电子邮箱"
            log_vals["before_change"] = use_company_id.linkman_email
            log_vals["after_change"] = linkman_email
            self.env[change_log_model].create(log_vals)

        province_id = vals.get("province_id", False)
        if province_id and province_id != use_company_id.province_id.id:
            province = self.env["tyibs.base.province"].browse(province_id)
            log_vals["field_name"] = u"所属省份"
            log_vals["before_change"] = use_company_id.province_id.name
            log_vals["after_change"] = province.name
            self.env[change_log_model].create(log_vals)

        city_id = vals.get("city_id", False)
        if city_id and city_id != use_company_id.city_id.id:
            city = self.env["tyibs.base.province.city"].browse(city_id)
            log_vals["field_name"] = u"所属城市"
            log_vals["before_change"] = use_company_id.city_id.name
            log_vals["after_change"] = city.name
            self.env[change_log_model].create(log_vals)

        area_id = vals.get("area_id", False)
        if area_id and area_id != use_company_id.area_id.id:
            area = self.env["tyibs.base.province.city.area"].browse(area_id)
            log_vals["field_name"] = u"所属区域"
            log_vals["before_change"] = use_company_id.area_id.name
            log_vals["after_change"] = area.name
            self.env[change_log_model].create(log_vals)

        address_detail = vals.get("address_detail", False)
        if address_detail and address_detail != use_company_id.address_detail:
            log_vals["field_name"] = u"详细地址"
            log_vals["before_change"] = use_company_id.address_detail
            log_vals["after_change"] = address_detail
            self.env[change_log_model].create(log_vals)

    @api.onchange("use_company_id")
    def _onchange_use_company_id(self):
        company = self.use_company_id
        if company:
            value = {
                "name": company.name,
                "linkman": company.linkman,
                "linkman_te": company.linkman_tel,
                "linkman_phone": company.linkman_phone,
                "linkman_email": company.linkman_email,
                "province_id": company.province_id,
                "city_id": company.city_id,
                "area_id": company.area_id,
                "address_detail": company.address_detail,
            }
            return {"value": value}

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        if context.get("search_from", False) == "use_menu":
            args.append(("use_company_id", "=", self.env.user.use_company_id.id))
        elif context.get("search_from", False) == "qs_area":
            args.append(("use_company_id.area_id", "=", self.env.user.qs_company_id.area_id.id))
        return super(FilingUserCompanyApply, self).search(args, offset, limit, order, count)


class FilingChangeLog(models.Model):
    """
    工单变更记录
    """
    _name = "tyibs.base.filing.change.log"

    field_name = fields.Char(string=u"变更项", size=20)
    before_change = fields.Char(string=u"变更前", size=200)
    after_change = fields.Char(string=u"变更后", size=200)
    res_model = fields.Char(string=u"关联的模型", size=200)
    res_id = fields.Char(string=u"关联的ID", size=200)


class FilingUseCompanyChangeApply(models.Model):
    """
    使用单位变更工单
    """

    _name = "tyibs.base.filing.use.company.change.apply"
    _description = u"使用单位变更审核"
    _rec_name = "order_number"
    _order = "id desc"

    order_number = fields.Char(string=u"工单号", required=True, readonly=True,
                               default=lambda self: self.env["ir.sequence"].next_by_code("tyibs.base.use.company.change.apply.sequence"))
    old_use_company_id = fields.Many2one("tyibs.base.lift.use.company", string=u"变更前使用单位", required=True, default=lambda self: self.env.user.use_company_id)
    new_use_company_id = fields.Many2one("tyibs.base.lift.use.company", string=u"变更后使用单位", required=True, domain="[('id', '!=', old_use_company_id)]", context={'search_scope': 'all'})
    lift_ids = fields.Many2many("tyibs.base.lift","tyibs_base_filing_use_company_change_lift_rel", "use_company_id", "lift_id", string=u"电梯", domain="[('use_company_id', '=', old_use_company_id)]", required=True)
    state = fields.Selection(APPLY_STATE,
                             string=u'审批状态', default='pending')
    log_ids = fields.Many2many("tyibs.base.common.log", "tyibs_base_use_company_change_common_log_rel", "apply_id", "log_id",
                                     domain="[('res_model', '=', 'tyibs.base.filing.use.company.change.apply'), ('res_id', '=', id)]",
                                     string=u"审核记录")

    def origin_write(self, vals):
        return super(FilingUseCompanyChangeApply, self).write(vals)

    @api.one
    def approve(self):
        """
        审核通过
        :return:
        """
        # 绑定使用单位
        self.lift_ids.write({'use_company_id': self.new_use_company_id.id})
        self.origin_write({
            'state': 'approved',
            'log_ids': [(0, False, {
                'res_model': self._name,
                'res_id': self.id,
                'user_id': self.env.uid,
                'content': u"审核通过",
                'time': datetime.utcnow()
            })]
        })

    @api.multi
    def write(self, vals):
        """
        审核过的工单不可以修改
        :param vals:
        :return:
        """
        if self.state == "approved":
            raise Warning(u"工单已经审核，不可以修改。")
        vals["state"] = "pending"
        return super(FilingUseCompanyChangeApply, self).write(vals)

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        if context.get("search_from", False) == "use_menu":
            args.append(("old_use_company_id", "=", self.env.user.use_company_id.id))
        elif context.get("search_from", False) == "qs_area":
            args.append(("old_use_company_id.area_id", "=", self.env.user.qs_company_id.area_id.id))
        return super(FilingUseCompanyChangeApply, self).search(args, offset, limit, order, count)


            # @api.model
    # def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
    #     context = self._context or {}
    #     res = super(FilingUseCompanyChangeApply, self).fields_view_get(view_id=view_id, view_type=view_type,
    #                                                  toolbar=toolbar, submenu=False)
    #
    #     if res['type'] == "form":
    #         from lxml import etree
    #         asset_id = self.env.context.get('active_id')
    #         active_model = self.env.context.get('active_model')
    #         if context.get("form_no_edit", False) == 'no':
    #             doc = etree.XML(res['arch'])
    #             doc.xpath("//form")[0].set("edit", "false")
    #             res['arch'] = etree.tostring(doc)
    #     return res


class CommonLog(models.Model):
    """
    通用审核记录
    """

    _name = "tyibs.base.common.log"
    _order = "time desc"

    res_model = fields.Char(string=u"关联的模型", size=200)
    res_id = fields.Char(string=u"关联的ID", size=200)
    user_id = fields.Many2one("res.users", string=u"处理人")
    content = fields.Char(string=u"处理内容", size=300)
    time = fields.Datetime(string=u"处理时间")


class FilingMaintenanceEmployeeResignApply(models.Model):
    """
    维保单位在增加员工时发现员工在其它公司没有辞职的时候发起的申请
    """
    _name = "tyibs.base.filing.maintenance.employee.resign.apply"
    _description = u"员工辞职申请"
    _rec_name = "employee_id"
    _order = 'apply_time desc'

    employee_id = fields.Many2one("tyibs.base.maintenance.company.employee", string=u"员工", required=True, domain="[('has_dimission', '=', False)]")
    code = fields.Char(related="employee_id.code", store=True, readonly=True)
    mobile = fields.Char(related="employee_id.mobile", store=True, readonly=True)
    phone = fields.Char(related="employee_id.phone", store=True, readonly=True)
    identification_id = fields.Char(related="employee_id.identification_id", store=True, readonly=True)
    email = fields.Char(related="employee_id.email", store=True, readonly=True)
    birthday = fields.Date(related="employee_id.birthday", store=True, readonly=True)
    contract_date = fields.Date(related="employee_id.contract_date", store=True, readonly=True)
    contract_over_time = fields.Boolean(related="employee_id.contract_over_time", store=True, readonly=True)
    gender = fields.Selection([
        ('male', u'男性'),
        ('female', u'女性'),
        ('other', u'其他')
    ], related="employee_id.gender", store=True, readonly=True)

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", related="employee_id.enterprise_id", store=True, readonly=True)
    department_id = fields.Many2one('tyibs.base.maintenance.company.department', related="employee_id.department_id", store=True, readonly=True)
    has_dimission = fields.Boolean(related="employee_id.has_dimission", store=True, readonly=True)
    image = fields.Binary(related="employee_id.image", attachment=True, store=True, readonly=True)
    image_medium = fields.Binary(related="employee_id.image_medium", attachment=True, store=True, readonly=True)
    image_small = fields.Binary(related="employee_id.image_small", attachment=True, store=True, readonly=True)
    certificate_ids = fields.One2many("tyibs.base.maintenance.company.employee.certificate", "employee_id", related="employee_id.certificate_ids", store=True, readonly=True)
    res_user_id = fields.Many2one("res.users", related="employee_id.res_user_id", store=True, readonly=True)
    notes = fields.Text(related="employee_id.notes", store=True, readonly=True)

    state = fields.Selection(APPLY_STATE, string=u"审批状态", default="pending")
    proposer = fields.Many2one("res.users", string=u"申请人", default=lambda self: self.env.uid, readonly=True)
    apply_time = fields.Datetime(string=u"申请时间", default=datetime.utcnow(), readonly=True)
    log_ids = fields.Many2many("tyibs.base.common.log", "tyibs_base_main_employee_resign_common_log_rel", "apply_id",
                               "log_id",
                               domain="[('res_model', '=', 'tyibs.base.filing.maintenance.employee.resign.apply'), ('res_id', '=', id)]",
                               string=u"审核记录")

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        if context.get("search_from", False) == "qs_area":
            args.append(('enterprise_id.area_id', '=', self.env.user.qs_company_id.area_id.id))
        if context.get("search_from", False) == "main_menu":
            args.append(('proposer', '=', self.env.uid))
        return super(FilingMaintenanceEmployeeResignApply, self).search(args, offset, limit, order, count)

    def origin_write(self, vals):
        # 跳过write的方法直接走父类write
        return super(FilingMaintenanceEmployeeResignApply, self).write(vals)

    @api.one
    def approve(self):
        """
        审核通过
        :return:
        """
        self.write({
            'state': 'approved',
            'log_ids': [(0, False, {
                'res_model': self._name,
                'res_id': self.id,
                'user_id': self.env.uid,
                'content': u"审核通过",
                'time': datetime.utcnow()
            })]
        })
        self.employee_id.write({'has_dimission': True})
        return True
